#' ---
#' title: "More donors, more democracy: Appendix B: The instrumental variable approach"
#' subtitle: "Distribution of aid shares by female-legislator share quartiles"
#' output:
#'   pdf_document:
#'     toc: true
#'     number_sections: true
#' author: Sebastian Ziaja
#' date: "This version: 2 November 2018"
#' ---

#+ setup

workdir <- ""
# workdir <- ifelse(basename(getwd()) == "aiddem_new", "", "../")
source(paste0(workdir, "scripts/load_packages.R"))
source(paste0(workdir, "scripts//extract.custom.R"))
source(paste0(workdir, "scripts//functions.R"))
source(paste0(workdir, "scripts//formulas.R"))
source(paste0(workdir, "scripts//variable_labels.R"))
source(paste0(workdir, "scripts//getData.R"))
source(paste0(workdir, "scripts//aggData.R"))


## aid from countries with many women different -------------

# source(paste0(workdir, "scripts/generateDemAid.R"))
daid <- read_rds(paste0(workdir, "data/daid.rds"))


    dsub <-
        daid %>%
        filter(com > 0) %>%
        select(don, year, com, wipquant,
               civsoc, compart, grass, otherpart, elections,
               hr, freeflow, womorg) %>%
        melt(id = c("don", "year", "com", "wipquant")) %>%
        filter(value == 1, !is.na(wipquant)) %>%
        select(-value) %>%
        group_by(don, year, wipquant, variable) %>%
        summarise(com = sum(com, na.rm = TRUE)) %>%
        ungroup %>%
        group_by(don, year) %>%
        mutate(comtotal = sum(com, na.rm = TRUE),
               comshare = 100 * com / comtotal) %>%
        ungroup %>%
        mutate(wipqf = as.factor(wipquant))

sld <- as.data.frame(sectlabtab)
names(sld) <- c("label", "variable")

dsub <- left_join(dsub, sld, by = "variable")

    ggplot(dsub,
           aes(x = comshare, fill = wipqf)) +
        geom_density(alpha = 0.25) +
        coord_cartesian(ylim = c(0, .075)) +
        facet_wrap(~ label) +
        xlab("Percentage of overall civil society aid") +
        ylab("Density") +
        guides(fill = guide_legend(title = "Female legislator\nshare quartiles")) +
        theme_bw() +
        theme(legend.position=c(.83,.15)) +
        ggsave(paste0(workdir, "graphs/demaid_shares_by_wip_quartiles.pdf")
               , width = 5, height = 7
               )
